package com.lyshop.guiyingshanding.application;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.bun.miitmdid.core.JLibrary;
import com.google.gson.Gson;
import com.hihonor.ads.identifier.AdvertisingIdClient;
import com.lyshop.guiyingshanding.constants.Constant;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.commonsdk.listener.OnGetOaidListener;
import com.umeng.umcrash.IUMCrashCallbackWithType;
import com.umeng.umcrash.UMCrash;
import com.lyshop.guiyingshanding.R;
import com.lyshop.guiyingshanding.bean.ClientBean;
import com.lyshop.guiyingshanding.bean.GifBean;
import com.lyshop.guiyingshanding.bean.HomeData;
import com.lyshop.guiyingshanding.bean.ImageItemBean;
import com.lyshop.guiyingshanding.bean.ImportantBean;
import com.lyshop.guiyingshanding.bean.LatestProPriceBean;
import com.lyshop.guiyingshanding.bean.NewsNoticeBean;
import com.lyshop.guiyingshanding.bean.SellOrderInfoBean;
import com.lyshop.guiyingshanding.bean.ShopGoodsListBean;
import com.lyshop.guiyingshanding.bean.UserInfoBean;
import com.lyshop.guiyingshanding.bean.VersionBean;
import com.lyshop.guiyingshanding.core.AppAction;
import com.lyshop.guiyingshanding.core.AppActionImpl;
import com.lyshop.guiyingshanding.eventbus.EventCenter;
import com.lyshop.guiyingshanding.eventbus.EventConstants;
import com.lyshop.guiyingshanding.net.ActionCallbackListener;
import com.lyshop.guiyingshanding.utils.AppLifecycleListener;
import com.lyshop.guiyingshanding.utils.ClientUtil;
import com.lyshop.guiyingshanding.utils.DataUtils;
import com.lyshop.guiyingshanding.utils.LogUtil;
import com.lyshop.guiyingshanding.utils.MiitHelper;
import com.lyshop.guiyingshanding.utils.ToastUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.zc.mychart.model.GoodsAllBean;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cn.jpush.android.api.JPushInterface;

public class MyApplication extends Application {
    public static final String TCP_PRICE_CHANGE_ACTION = "Jli_tcp_price_change_action";//价格变化
    public static final String GO_TO_REFRESH_ACCOUNT = "Jli_refresh_account";//刷新用户数据
    public static final String GO_TO_MAIN_WELFARE = "Jli_go_to_main_welfare_action";
    public static final String GO_TO_ORDER_ACTION = "Jli_go_to_order_action";//去下单
    private static MyApplication mApplication;
    private AppAction appAction;
    private List<GoodsAllBean> mAllList = new ArrayList<>();
    private Map<String, GoodsAllBean> allGoodMap = new HashMap<>();
    private Map<String, GifBean> mGifMap = new HashMap<>();
    private static final String HUAWEI_BRAND = "HONOR";//荣耀手机
    private static final String OTHER_BRAND = "OTHER";//其他机型

    static {//static 代码段可以防止内存泄露
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.color_f2f3f5, R.color.color_text_86909c);//全局设置主题颜色
                return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
    }

    private ExecutorService executor;
    private AppLifecycleListener lifecycleListener;
    private ImportantBean importantBean;//重要数据
    private List<NewsNoticeBean> newsNoticeBeans;//重要通知
    private List<ImageItemBean> bannerBeans;//banner
    private List<SellOrderInfoBean> sellOrderInfoBeans;//牛单广场
    private VersionBean versionBean;//版本升级
    private List<ShopGoodsListBean> shopGoodsListBeans;//零售商品
    private String authSecret;//一键登录密钥

    @Override
    public void onCreate() {
        super.onCreate();
        int pid = android.os.Process.myPid();
        String processAppName = getAppName(pid);
        // 如果APP启用了远程的service，此application:onCreate会被调用2次，默认的APP会在以包名为默认的process name下运行，如果查到的process name不是APP的process name就立即返回
        if (processAppName == null || !processAppName.equalsIgnoreCase(getPackageName())) {
            LogUtil.e("dangzt", "appliaction onCreate重复");
            // 则此application::onCreate 是被service 调用的，直接返回
            return;
        }

        LogUtil.e("dangzt", "appliaction onCreate");
        //本地库初始化
        mApplication = this;
        appAction = new AppActionImpl(this);
        LogUtil.e("dangzt", "appAction 地址" + appAction);
        lifecycleListener = new AppLifecycleListener();
        registerActivityLifecycleCallbacks(lifecycleListener);
        setClientId();
        //友盟预加载
        UMConfigure.preInit(this, Constant.YM_KEY, DataUtils.getClientName(this));

        boolean isAgree = DataUtils.getAgreeState(this);
        if (isAgree) {
            //初始化三方
            initOther();
        }
    }

    private String getAppName(int pID) {
        String processName = null;
        ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        PackageManager pm = this.getPackageManager();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try {
                if (info.pid == pID) {
                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
                // Log.d("Process", "Error>> :"+ e.toString());
            }
        }
        return processName;
    }

    public static MyApplication getApplication() {
        return mApplication;
    }

    /**
     * 所有网络请求
     * @return
     */
    public AppAction getAppAction() {
        return appAction;
    }

    public void initOther(){
        LogUtil.e("dangzt", "初始化三方操作");
        setDeviceId();
        // 创建一个固定大小的线程池
        executor = Executors.newFixedThreadPool(1);
        // 初始化定时任务
        mHandler.post(mRefreshMarketUI);
        mHandler.post(mRefreshFollowUI);
        //授权初始化
//        XXPermissions.setInterceptor(new PermissionInterceptor());
        //第三方初始化操作
        JLibrary.InitEntry(this);
        //极光初始化
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
        //友盟预加载
        UMConfigure.preInit(this, Constant.YM_KEY, DataUtils.getClientName(this));
        //友盟初始化
        UMConfigure.setLogEnabled(true);
        UMConfigure.init(this, Constant.YM_KEY, DataUtils.getClientName(this), UMConfigure.DEVICE_TYPE_PHONE, "");
        UMConfigure.getOaid(MyApplication.getApplication(), new OnGetOaidListener() {
            @Override
            public void onGetOaid(String s) {
                if (!TextUtils.isEmpty(s)){
                    DataUtils.setOAID(MyApplication.getApplication(), s);
                }
                LogUtil.d("dangzt", "oaid=====" + DataUtils.getOAID(MyApplication.getApplication()));
            }
        });
        UMCrash.registerUMCrashCallback(new IUMCrashCallbackWithType() {
            @Override
            public String onCallback(CrashType type) {
                switch (type) {
                    case CRASH_TYPE_NATIVE:
                        return "Native 崩溃时register的自定义内容字符串";
                    case CRASH_TYPE_JAVA:
                        return "JAVA 崩溃时register的自定义内容字符串";
                    case CRASH_TYPE_ANR:
                        return "ANR 时register的自定义内容字符串";
                    case CRASH_TYPE_CUSTOM_LOG:
                        return "自定义错误 register的自定义内容字符串";
                    case CRASH_TYPE_BLOCK:
                        return "卡顿 时register的自定义内容字符串";
                    default:
                        return null;
                }
            }
        });
    }

    /**
     * 更新用户信息
     */
    public void updateUserDetail(){
        appAction.getUserDetail(new ActionCallbackListener<UserInfoBean>() {
            @Override
            public void onSuccess(UserInfoBean data) {
                //设置用户数据
                DataUtils.setUserInfo(mApplication, data);
                if (data.noviceCoupon != null){
                    EventBus.getDefault().postSticky(new EventCenter<UserInfoBean>(EventConstants.EVENTCODE_NOVICE_TICKET));
                }
                //发送用户数据更新事件
                EventBus.getDefault().post(new EventCenter<UserInfoBean>(EventConstants.EVENTCODE_UPDATE_USER));
            }

            @Override
            public void onFailure(String errorCode, String message) {
                ToastUtil.showToast(mApplication, message);
            }
        });
    }

    /**
     * 获取渠道密钥和渠道号
     */
    private void setClientId() {
        ApplicationInfo appInfo = null;
        try {
            appInfo = getApplicationContext().getPackageManager().getApplicationInfo(getApplicationContext().getPackageName(), PackageManager.GET_META_DATA);
        } catch (PackageManager.NameNotFoundException e1) {
            e1.printStackTrace();
        }

        //从清单文件中获取这个渠道值
        String client = appInfo.metaData.getString("CHANNEL_NAME");
        LogUtil.e("dangzt", "client_id = " + client);

        ClientBean mClientBean = ClientUtil.getInstance().getClientBean(client);
        if (null != mClientBean) {
            DataUtils.setClientId(this, String.valueOf(mClientBean.client_id));
            DataUtils.setClientName(this, client);
            DataUtils.setSignKey(this, mClientBean.sign_key);

            LogUtil.e("dangzt", client);
            LogUtil.e("dangzt", "client_id = " + mClientBean.client_id);
            LogUtil.e("dangzt", "sign_key = " + mClientBean.sign_key);
        }
    }

    /**
     * 设置设备id
     */
    private void setDeviceId() {
        new Thread(() -> {
            String deviceId = DataUtils.getDeviceId(MyApplication.this);
            if (!TextUtils.isEmpty(deviceId)){
                DataUtils.setUUID(MyApplication.this, deviceId);
            }

//            String brand = Build.BRAND.toUpperCase();
//            if (HUAWEI_BRAND.equals(brand)) {
//                getHuaweiOaid();
//            } else {
//                getOtherOaid();
//            }
            LogUtil.d("dangzt", "uuid=====" + DataUtils.getUUID(this));
        }).start();
    }

    private static void getHuaweiOaid() {
        // 使用华为SDK获取OAID的方法
        try {
            AdvertisingIdClient.Info info = AdvertisingIdClient.getAdvertisingIdInfo(mApplication);
            if (null != info) {
                if (!TextUtils.isEmpty(info.id)){
                    DataUtils.setOAID(mApplication, info.id);
                }
            }
        } catch (Exception e) {
            Log.i("dangzt", "getAdvertisingIdInfo Exception: " + e.toString());
        }
    }

    private static void getOtherOaid() {
        // 其他手机品牌获取OAID的方法
        MiitHelper helper = new MiitHelper(ids -> {
            if (!TextUtils.isEmpty(ids) || !ids.contains("0000")) {
                DataUtils.setOAID(mApplication, ids);
            }
        });
        helper.getDeviceIds(mApplication);
    }

    public void initAllHomeData(final ActionCallbackListener<HomeData> listener){
        appAction.getHomeData("android", new ActionCallbackListener<HomeData>() {
            @Override
            public void onSuccess(HomeData data) {
                if (listener != null) {
                    listener.onSuccess(data);
                }
                importantBean = data.important;
                newsNoticeBeans = data.notice;
                bannerBeans = data.banner;
                sellOrderInfoBeans = data.orderProfit;
                versionBean = data.version;
                shopGoodsListBeans = data.retail;
                authSecret = data.authSecret;

                mAllList = data.contract;
                for (int i = 0; i < data.contract.size(); i++) {
                    GoodsAllBean goodsAllBean = data.contract.get(i);
                    allGoodMap.put(goodsAllBean.pro_code, goodsAllBean);
                }

                for (int i = 0; i < data.gif.size(); i++) {
                    mGifMap.put(data.gif.get(i).type, data.gif.get(i));
                }
            }

            @Override
            public void onFailure(String errorCode, String message) {
                if (listener != null) {
                    listener.onFailure(errorCode, message);
                }
            }
        });
    }

    /**
     * 初始化首页数据
     * @param listener
     */
//    public void initHomeData(final ActionCallbackListener<List<GoodsAllBean>> listener) {
//        appAction.getAllList(new ActionCallbackListener<List<GoodsAllBean>>() {
//            @Override
//            public void onSuccess(List<GoodsAllBean> data) {
//                if (listener != null){
//                    listener.onSuccess(data);
//                }
//                if (data.isEmpty())return;
//
//                allGoodMap.clear();
//                mAllList.clear();
//
//                mAllList = data;
//                for (int i = 0; i < data.size(); i++) {
//                    GoodsAllBean goodsAllBean = data.get(i);
//                    allGoodMap.put(goodsAllBean.pro_code, goodsAllBean);
//                }
//            }
//
//            @Override
//            public void onFailure(String errorCode, String message) {
//                if (listener != null){
//                    listener.onFailure(errorCode, message);
//                }
//            }
//        });
//    }

    /**
     * 初始化广告位
     * @param listener
     */
    public void initGifList(ActionCallbackListener<List<GifBean>> listener){
        appAction.getGifList(new ActionCallbackListener<List<GifBean>>() {
            @Override
            public void onSuccess(List<GifBean> data) {
                if (data == null || data.isEmpty()) return;
                for (int i = 0; i < data.size(); i++) {
                    mGifMap.put(data.get(i).type, data.get(i));
                }
                if (listener != null){
                    listener.onSuccess(data);
                }
            }

            @Override
            public void onFailure(String errorCode, String message) {
                if (listener != null){
                    listener.onFailure(errorCode, message);
                }
            }
        });
    }

    /**
     * 推广上报
     */
    public void postAd(){
        appAction.adPost(new ActionCallbackListener<Void>() {
            @Override
            public void onSuccess(Void data) {
                LogUtil.e("dangzt", "推广上报成功");
            }

            @Override
            public void onFailure(String errorCode, String message) {
                LogUtil.e("dangzt", "推广上报失败");
            }
        });
    }


    public Map<String, GoodsAllBean> getAllGoodMap() {
        return allGoodMap;
    }

    public List<GoodsAllBean> getAllList() {
        return mAllList;
    }

    public Map<String, GifBean> getGifMap() {
        return mGifMap;
    }

    public ImportantBean getImportantBean() {
        return importantBean;
    }

    public List<NewsNoticeBean> getNewsNoticeBeans() {
        return newsNoticeBeans;
    }

    public List<ImageItemBean> getBannerBeans() {
        return bannerBeans;
    }

    public List<SellOrderInfoBean> getSellOrderInfoBeans() {
        return sellOrderInfoBeans;
    }

    public VersionBean getVersionBean() {
        return versionBean;
    }

    public List<ShopGoodsListBean> getShopGoodsListBeans() {
        return shopGoodsListBeans;
    }

    public String getAuthSecret(){
        return authSecret;
    }

    /**
     * 设置websocket数据
     * @param webSocketJson
     */
    public void setWebSocketJson(String webSocketJson) {
//        LogUtil.d(" =====" + webSocketJson);
        try {
            if (!TextUtils.isEmpty(webSocketJson)){
                updateAllGoods(webSocketJson);
            }
        }catch (Exception e){

        }
    }

    private Handler mHandler = new Handler(Looper.getMainLooper());
    private Runnable mRefreshMarketUI = new Runnable() {
        @Override
        public void run() {
//            LogUtil.d("dzt", "刷新合约view");
            // 刷新UI操作
            EventBus.getDefault().post(new EventCenter(EventConstants.EVENTCODE_UPDATE_PRO_PRICE));
            // 设置下一次刷新的时间点
            mHandler.postDelayed(this, 1000); // 1000毫秒=1秒
        }
    };

    private Runnable mRefreshFollowUI = new Runnable() {
        @Override
        public void run() {
//            LogUtil.d("dzt", "刷新跟单view");
            // 刷新UI操作
            EventBus.getDefault().post(new EventCenter(EventConstants.EVENTCODE_UPDATE_PRO_FOLLOW_PRICE));
            // 设置下一次刷新的时间点
            mHandler.postDelayed(this, 5000); // 1000毫秒=1秒
        }
    };


    private void updateAllGoods(String webSocketJson) {
        // 使用execute来异步执行数据处理
        executor.execute(new Runnable() {
            @Override
            public void run() {
                Gson gson = new Gson();
                LatestProPriceBean priceBean = gson.fromJson(webSocketJson, LatestProPriceBean.class);
                if (priceBean != null && !TextUtils.isEmpty(priceBean.content)){
                    String[] contentArray = priceBean.content.split("\\|");
                    GoodsAllBean goodsAllBean = allGoodMap.get(contentArray[0]);
                    if (goodsAllBean == null) return;
                    //价格或状态相等不需要处理
                    if (priceBean.type.equals("quote")
                            && goodsAllBean.latest_price == Double.parseDouble(contentArray[3])
                            && goodsAllBean.price_beginning == Double.parseDouble(contentArray[4])
                            && goodsAllBean.price_end_lastday == Double.parseDouble(contentArray[2])
                            && goodsAllBean.high_price == Double.parseDouble(contentArray[5])
                            && goodsAllBean.lowwest_price == Double.parseDouble(contentArray[6])) return;

                    if (priceBean.type.equals("state")
                    && goodsAllBean.during_type == Integer.parseInt(contentArray[1])) return;

                    //解析价格状态赋值
                    if (priceBean.type.equals("quote") && contentArray.length > 6){
                        priceBean.pro_code = contentArray[0];
                        priceBean.Update_time = contentArray[1];
                        priceBean.Price_end_lastday = Double.parseDouble(contentArray[2]);
                        priceBean.Latest_price = Double.parseDouble(contentArray[3]);
                        priceBean.Price_beginning = Double.parseDouble(contentArray[4]);
                        priceBean.High_price = Double.parseDouble(contentArray[5]);
                        priceBean.Lowwest_price = Double.parseDouble(contentArray[6]);
                    }else {
                        priceBean.pro_code = contentArray[0];
                        priceBean.During_type = Integer.parseInt(contentArray[1]);
                    }

                    if (priceBean.type.equals("state")){
                        goodsAllBean.during_type = priceBean.During_type;

                        for (int i = 0; i < mAllList.size(); i++) {
                            if (mAllList.get(i).pro_code.equals(priceBean.pro_code)) {
                                GoodsAllBean goodsAllBean1 = mAllList.get(i);
                                goodsAllBean1.during_type = priceBean.During_type;
                            }
                        }
                    }else {
                        if (goodsAllBean != null && priceBean != null) {
                            goodsAllBean.update_time = priceBean.Update_time;
                            goodsAllBean.latest_price = priceBean.Latest_price;
                            goodsAllBean.price_end_lastday = priceBean.Price_end_lastday;
                            goodsAllBean.price_beginning = priceBean.Price_beginning;
                            goodsAllBean.high_price = priceBean.High_price;
                            goodsAllBean.lowwest_price = priceBean.Lowwest_price;
                        }

                        for (int i = 0; i < mAllList.size(); i++) {
                            if (mAllList.get(i).pro_code.equals(priceBean.pro_code)) {
                                GoodsAllBean goodsAllBean1 = mAllList.get(i);
                                goodsAllBean1.update_time = priceBean.Update_time;
                                goodsAllBean1.latest_price = priceBean.Latest_price;
                                goodsAllBean1.price_end_lastday = priceBean.Price_end_lastday;
                                goodsAllBean1.price_beginning = priceBean.Price_beginning;
                                goodsAllBean1.high_price = priceBean.High_price;
                                goodsAllBean1.lowwest_price = priceBean.Lowwest_price;
                            }
                        }
                    }

                }
            }
        });
    }
}
